<template>
  <div id="teamCardList">
    <van-swipe-cell v-for="team in props.teamList" :key="team.id">
      <van-card
        :thumb="teamImg"
        :title="`${team.name}`"
        @click="toDetail(team.id, team.name)"
        @click-thumb.stop="showImagePreview([teamImg])"
      >
        <template #desc>
          <p
            style="white-space: normal; word-break: break-all; overflow: hidden"
          >
            {{ team.description }}
          </p>
        </template>
        <template v-if="props.qd != '0'" #tag>
          <van-tag
            mark
            :type="`${
              team.status == 0
                ? 'primary'
                : team.status == 1
                ? 'success'
                : 'danger'
            }`"
            style="margin-top: 8px"
          >
            {{ teamStatusEnum[team.status] }}
          </van-tag>
        </template>
        <template #bottom>
          <div v-if="team.expireTime">
            <p>
              过期时间:{{
                moment(Number(team.expireTime)).format("YYYY-MM-DD")
              }}
            </p>
          </div>
          <van-progress
            v-if="team?.hasJoinNum != team?.maxNum"
            :pivot-text="`${team.hasJoinNum}/${team.maxNum}`"
            :percentage="(team.hasJoinNum / team?.maxNum) * 100"
          />
          <van-progress
            v-else
            :pivot-text="`${team.hasJoinNum}/${team.maxNum}`"
            color="#ee0a24"
            :percentage="100"
          />
        </template>
        <template #price-top>
          <van-button
            plain
            size="small"
            type="primary"
            v-if="
              team.userId !== currentUser?.id &&
              team.ties !== 1 &&
              team.status != 1 &&
              team?.hasJoinNum != team?.maxNum
            "
            @click.stop="preJoinTeam(team)"
          >
            加入队伍
          </van-button>
          <van-button
            disabled
            size="small"
            type="primary"
            v-if="
              team.userId !== currentUser?.id &&
              team.ties !== 1 &&
              team?.hasJoinNum == team?.maxNum
            "
            plain
            @click.stop="preJoinTeam(team)"
          >
            队伍已满
          </van-button>
        </template>
      </van-card>
      <template
        #right
        v-if="props.qd != '0' && props.userId === currentUser.id"
      >
        <van-button
          square
          :text="`${props.qd == '1' ? '退出' : '解散'}`"
          type="danger"
          @click="quitOrDel(team.id, props.qd)"
          class="delete-button"
        />
        <van-button
          v-if="team?.userId === currentUser?.id"
          square
          type="primary"
          class="delete-button"
          @click.stop="doUpdateTeam(team.id)"
          >修改
        </van-button>
      </template>
    </van-swipe-cell>
    <van-dialog
      v-model:show="showPasswordDialog"
      title="请输入密码"
      show-cancel-button
      @confirm="doJoinTeam"
      @cancel="doJoinCancel"
    >
      <van-field clearable v-model="password" placeholder="请输入密码" />
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import moment from "moment";
import myAxios from "../plugins/myAxios";
import teamImg from "../assets/team.jpg";
import { useRouter } from "vue-router";
import { TeamType } from "../models/team";
import { UserType } from "../models/user";
import { inject, onMounted, ref } from "vue";
import { getCurrentUser } from "../services/user";
import { teamStatusEnum } from "../constants/team";
import {
  showSuccessToast,
  showFailToast,
  showConfirmDialog,
  showImagePreview,
} from "vant";

interface TeamCardListProps {
  teamList: TeamType[];
  qd: string; // 具体执行退出还是解散操作
  userId: number; // 被访者的id
}

const props = withDefaults(defineProps<TeamCardListProps>(), {
  // @ts-ignore
  teamList: [] as TeamType[],
});

const showPasswordDialog = ref(false); //展示队伍密码的弹出层
const joinTeamId = ref(0); //要加入的队伍id
const preJoinTeam = (team: TeamType) => {
  joinTeamId.value = team.id;
  if (team.status === 0) {
    showConfirmDialog({
      message: "确认加入队伍吗",
    })
      .then(async () => {
        doJoinTeam();
      })
      .catch(() => {});
  } else {
    showPasswordDialog.value = true;
  }
};

const router = useRouter();
const password = ref(""); //输入的队伍密码
const reload = inject("reload"); //刷新函数
const currentUser = ref({} as UserType); //当前用户
const doJoinTeam = async () => {
  if (!joinTeamId.value) {
    return;
  }
  const res = await myAxios.post("/team/join", {
    teamId: joinTeamId.value,
    password: password.value,
  });

  if (res?.code === 0) {
    if (props.userId === 0) {
      router.push({
        path: "/user/team",
        query: {
          userId: currentUser.value.id,
        },
      });
    } else {
      reload();
    }
    showSuccessToast("小智暖心提醒:入团成功");
    doJoinCancel();
  } else {
    showFailToast(
      `小智遗憾告知:${res?.message ?? "与服务器失联 请到上一个页面刷新重试"}`
    );
  }
};

//取消入团，重置信息
const doJoinCancel = () => {
  joinTeamId.value = 0;
  password.value = "";
};

const quitOrDel = async (teamId: number, qd: string) => {
  showConfirmDialog({
    message: `确认${qd == "1" ? "退出" : "解散"}队伍吗`,
  })
    .then(async () => {
      const res = await myAxios.post(
        qd == "1" ? "/team/quit" : "/team/delete",
        {
          teamId: teamId,
        }
      );
      if (res?.code === 0) {
        reload();
        showSuccessToast(`小智暖心提醒:${qd == "1" ? "退出" : "解散"}成功`);
      } else {
        showFailToast(
          "小智遗憾告知:操作失败" +
            (res.description ? `,${res.description}` : "")
        );
      }
    })
    .catch(() => {});
};

/**
 * 跳转队伍详情页
 * @param teamId
 */
const toDetail = (teamId: number, teamName: string) => {
  router.push({
    path: "/team/detail",
    query: {
      teamId,
      teamName,
      userId: currentUser.value.id,
    },
  });
};

/**
 * 跳转至修改队伍页
 * @param id
 */
const doUpdateTeam = (id: number) => {
  router.push({
    path: "/team/update",
    query: {
      id,
      userId: props.userId ?? currentUser.value.id,
    },
  });
};

onMounted(async () => {
  currentUser.value = await getCurrentUser("1");
});
</script>

<style scoped>
#teamCardList :deep(.van-image__img) {
  height: 8rem;
  object-fit: unset;
}
.delete-button {
  height: 100%;
}
</style>
